<?php
/**
 * @author yuanyitian
 * @date 2023/8/8 17:24
 */

namespace utils;

class wechat_pay
{
    //获取微信小程序体系接口所需token，且自动维护
    public function getToken(){
        $res = file_get_contents($GLOBALS["wechat_baseurl"] . "cgi-bin/token?appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"] . "&grant_type=client_credential" );
        $res = json_decode($res, true);

        if(isset($res['access_token'])){
            $redis = redis::con();
            $redis->setex('wechat_token', 7000, $res['access_token']);
            $redis->close();
            return $res["access_token"];
        }else{
            return '获取微信token失败！';
        }

    }

    //支付
    public static function get($order_no, $openid, $notify_url, $total)
    {
        $time = time();
        $data = [
            "appid" => $GLOBALS["wechat_appid"],
            "mchid" => $GLOBALS["wechat_mchid"],
            "description" => "商品购买退款",
            "out_trade_no" => $order_no,
            "notify_url" => $notify_url,
            "amount" => ["total" => $total],
            "payer" => ["openid" => $openid]
        ];
        $nonce_str = md5(mt_rand(10000000, 99999999) . time() . mt_rand(10000000, 99999999));
        $nonce_str0 = md5(mt_rand(10000000, 99999999) . time() . mt_rand(10000000, 99999999));


        openssl_sign("POST\n/v3/pay/transactions/jsapi\n" . $time . "\n" . $nonce_str . "\n" . json_encode($data) . "\n", $sign, openssl_pkey_get_private(file_get_contents($GLOBALS["wechat_key"])), 'sha256WithRSAEncryption');
        $res = http_pay($GLOBALS["wechat_pay_url"], 'Authorization: WECHATPAY2-SHA256-RSA2048 mchid="' . $GLOBALS["wechat_mchid"] . '",nonce_str="' . $nonce_str . '",signature="' . base64_encode($sign) . '",timestamp="' . $time . '",serial_no="' . (openssl_x509_parse(openssl_x509_read(file_get_contents($GLOBALS["wechat_cert"]))))["serialNumberHex"] . '"', "POST", $data);

        if(!isset($res['prepay_id'])){
            return out_error($res['message']);
        }
        openssl_sign($GLOBALS["wechat_appid"] . "\n" . $time . "\n" . $nonce_str0 . "\n" . "prepay_id=" . $res["prepay_id"] . "\n", $sign0, openssl_pkey_get_private(file_get_contents($GLOBALS["wechat_key"])), 'sha256WithRSAEncryption');

        $out["timeStamp"] = $time;
        $out["nonceStr"] = $nonce_str0;
        $out["package"] = "prepay_id=" . $res["prepay_id"];
        $out["signType"] = "RSA";
        $out["paySign"] = base64_encode($sign0);
        return out_right($out);
    }

    //退款
    public static function refund($out_trade_no, $notify_url, $total, $refund)
    {
        $time = time();
        $data = [
            "out_refund_no" => "refund" . $out_trade_no,
            "out_trade_no" => $out_trade_no,
            "notify_url" => $notify_url,
            "amount" => [
                "refund" => (int)$refund,
                "total" => (int)$total,
                "currency" => "CNY"
            ]

        ];
        $nonce_str = md5(mt_rand(10000000, 99999999) . time() . mt_rand(10000000, 99999999));


        openssl_sign("POST\n/v3/refund/domestic/refunds\n" . $time . "\n" . $nonce_str . "\n" . json_encode($data) . "\n", $sign, openssl_pkey_get_private(file_get_contents($GLOBALS["wechat_key"])), 'sha256WithRSAEncryption');
        return http_pay($GLOBALS["wechat_refund_url"], 'Authorization: WECHATPAY2-SHA256-RSA2048 mchid="' . $GLOBALS["wechat_mchid"] . '",nonce_str="' . $nonce_str . '",signature="' . base64_encode($sign) . '",timestamp="' . $time . '",serial_no="' . (openssl_x509_parse(openssl_x509_read(file_get_contents($GLOBALS["wechat_cert"]))))["serialNumberHex"] . '"', "POST", $data);

    }

    //打款至供应商微信零钱
    public static function pay_to_supplier($data)
    {


        $remark=$data["remark"];
        $time = time();
        openssl_public_encrypt("袁一天", $name_sign, file_get_contents($GLOBALS["wechat_client_cert"]), OPENSSL_PKCS1_OAEP_PADDING);
        $name_sign=base64_encode($name_sign);
        $data = [
            "appid" => $GLOBALS["wechat_appid"],
            "out_batch_no" => rand(10000, 99999) . time() . rand(10000, 99999),
            "batch_name" => $remark,
            "batch_remark" => $remark,
            "total_amount" => 40,
            "total_num" => 1,
            "transfer_detail_list" => [
                [
                    "out_detail_no" => "list" . rand(10000, 99999) . time() . rand(10000, 99999),
                    "transfer_amount" => 40,
                    "transfer_remark" => $remark,
                    "openid" => "o1V6G60M_wyuLLBLAvb9dqtWSkvs",
                    "user_name" => $name_sign
                ]
            ]

        ];
        $nonce_str = md5(mt_rand(10000000, 99999999) . time() . mt_rand(10000000, 99999999));


        openssl_sign("POST\n/v3/transfer/batches\n" . $time . "\n" . $nonce_str . "\n" . json_encode($data) . "\n", $sign, openssl_pkey_get_private(file_get_contents($GLOBALS["wechat_key"])), 'sha256WithRSAEncryption');
        return http_pay_to_supplier($GLOBALS["wechat_pay_to_supplier"], 'Authorization: WECHATPAY2-SHA256-RSA2048 mchid="' . $GLOBALS["wechat_mchid"] . '",nonce_str="' . $nonce_str . '",signature="' . base64_encode($sign) . '",timestamp="' . $time . '",serial_no="' . (openssl_x509_parse(openssl_x509_read(file_get_contents($GLOBALS["wechat_cert"]))))["serialNumberHex"] . '"', "POST", $data);

    }

    public static function decode($data){
        $ciphertext = base64_decode($data["data"][0]["encrypt_certificate"]["ciphertext"]);
        $nonce = $data["data"][0]["encrypt_certificate"]["nonce"];
        $associatedData = $data["data"][0]["encrypt_certificate"]["associated_data"];
        $key = $GLOBALS["wechat_pay_key"];

        $client_cert = openssl_decrypt(substr($ciphertext, 0, -16), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, substr($ciphertext, -16), $associatedData);
        return $client_cert;
    }



}